//
//  ViewController.m
//  aigo
//
//  Created by Tai Truong on 11/20/12.
//  Copyright (c) 2012 AIGO. All rights reserved.
//

#import "AppViewController.h"

@interface AppViewController ()

@end


@implementation AppViewController
@synthesize configDataModel = _configDataModel;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        _listOfViewController = [NSMutableArray new];
        self.configDataModel = [[VKConfigDataModel alloc] init];
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view, typically from a nib.
//    UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(30, 30, 100, 30)];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/////////////////////////////////
static AppViewController *_appVCInstance;
+ (AppViewController *)Shared
{
    if (!_appVCInstance) {
        _appVCInstance = [[AppViewController alloc] init];
    }
    return _appVCInstance;
}

#pragma mark - Indicator view animation

- (void)isRequesting:(BOOL)isRe andRequestType:(ENUM_API_REQUEST_TYPE)type andFrame:(CGRect)frame {
    if (isRe) {
        if (_requestingView == nil) {
            _requestingView = [UIView new];
            _requestingView.backgroundColor = [UIColor blackColor];
            _requestingView.alpha= 0.5;
        }
        if (_requestingIndicator == nil) {
            _requestingIndicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
            [_requestingView addSubview:_requestingIndicator];
            
        }
        
        [_requestingView removeFromSuperview];
        [_requestingIndicator startAnimating];
		_requestingView.frame = frame;
		_requestingIndicator.center = CGPointMake(frame.size.width / 2, frame.size.height / 2);
        [[[_listOfViewController lastObject] view] addSubview:_requestingView];
    }
    else {
        [_requestingIndicator stopAnimating];
        [_requestingView removeFromSuperview];
    }
}

#pragma mark - App Protocol
/////////////////////////////////
- (void)update {
    // update top view controller
    if ([_listOfViewController lastObject]) {
        id<AppViewControllerProtocol> vc = [_listOfViewController lastObject];
        if ([vc respondsToSelector:@selector(update)]) {
            [vc update];
        }
    }
    
    // Request API server automatically
    if ([[AutomationDataManager Shared] respondsToSelector:@selector(update)]) {
        [[AutomationDataManager Shared] update];
    }
}

#pragma mark - Home View Controller
/////////////////////////////////
- (void)changeToHomeFromWelcomeScreen:(BOOL)isFromLogin {
    if (isFromLogin) {
        [_listOfViewController removeAllObjects];
        [self.navigationController popToRootViewControllerAnimated:NO];
    }

#ifdef __CLIENT__
    // CLIENT
    ClientMainViewController *clientVC = [ClientMainViewController new];
    [_listOfViewController addObject:clientVC];
    [self.navigationController pushViewController:clientVC animated:YES];
#else
    // DRIVER
    DriverMainViewController *driverVC = [DriverMainViewController new];
    [_listOfViewController addObject:driverVC];
    [self.navigationController pushViewController:driverVC animated:YES];
#endif

}
- (void)changeBackToHome {
    [_listOfViewController removeAllObjects];
    
    CATransition* transition = [CATransition animation];
    transition.duration = TIMER_CHANGING_VIEW;
    transition.type = kCATransitionPush;
    transition.subtype = kCATransitionFromLeft;
    [self.navigationController.view.layer addAnimation:transition forKey:kCATransition];
    
    [_listOfViewController removeAllObjects];
    [self.navigationController popToRootViewControllerAnimated:NO];
    
#ifdef __RELEASE__PRODUCTION1__
    // CLIENT
    ClientMainViewController *clientVC = [ClientMainViewController new];
    [_listOfViewController addObject:clientVC];
    [self.navigationController pushViewController:clientVC animated:YES];
#else
    // DRIVER
    ClientMainViewController *clientVC = [ClientMainViewController new];
    [_listOfViewController addObject:clientVC];
    [self.navigationController pushViewController:clientVC animated:YES];
#endif
}

#pragma mark - Splash Screen View Controller
/////////////////////////////////
- (void)changeToSplashScreen {
    SplashScreenViewController *tempVC = [SplashScreenViewController new];
    
    [_listOfViewController addObject:tempVC];
    [self.navigationController pushViewController:tempVC animated:NO];
}
- (void)changeBackFromSplashScreen {
    [_listOfViewController removeLastObject];
    [self.navigationController popViewControllerAnimated:NO];
    
    // MinhPB 2012/11/20
    [self changeToWelcome];
}

#pragma mark - Welcome
/////////////////////////////////
- (void)changeToWelcome {
    if ([UserDataManager Shared].loginStatus) {
        [self changeToHomeFromWelcomeScreen:NO];
    }
    else {
        WelcomeViewController *tempVC = [WelcomeViewController new];
        
        [_listOfViewController addObject:tempVC];
        [self.navigationController pushViewController:tempVC animated:NO];
    }
}
- (void)changeBackToWelcome {
    [_listOfViewController removeAllObjects];
    
    CATransition* transition = [CATransition animation];
    transition.duration = TIMER_CHANGING_VIEW;
    transition.type = kCATransitionPush;
    transition.subtype = kCATransitionFromLeft;
    [self.navigationController.view.layer addAnimation:transition forKey:kCATransition];
    [self.navigationController popToRootViewControllerAnimated:NO];
    
    WelcomeViewController *welcomeVC = [WelcomeViewController new];
    
    [_listOfViewController addObject:welcomeVC];
    [self.navigationController pushViewController:welcomeVC animated:NO];
}

#pragma mark - ProfileSetting
/////////////////////////////////
- (void)changeToProfileSetting {
    ProfileSettingViewController *tempVC = [ProfileSettingViewController new];
    
    [_listOfViewController addObject:tempVC];
    [self.navigationController pushViewController:tempVC animated:YES];
}
- (void)changeBackFromProfileSetting {
    [_listOfViewController removeLastObject];
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - Login & Register
/////////////////////////////////
- (void)changeToLogin {
    LoginViewController *tempVC = [LoginViewController new];
    
    [_listOfViewController addObject:tempVC];
    [self.navigationController pushViewController:tempVC animated:YES];
}
- (void)changeBackFromLogin {
    [_listOfViewController removeLastObject];
    [self.navigationController popViewControllerAnimated:YES];
}

/////////////////////////////////
- (void)changeToRegister {
    RegisterViewController *tempVC = [RegisterViewController new];
    
    [_listOfViewController addObject:tempVC];
    [self.navigationController pushViewController:tempVC animated:YES];
}
- (void)changeBackFromRegister {
    [_listOfViewController removeLastObject];
    [self.navigationController popViewControllerAnimated:YES];
}

/////////////////////////////////
- (void)changeToRecoveryPassword
{
    RecoveryPasswordViewController *reVC = [RecoveryPasswordViewController new];
    [_listOfViewController addObject:reVC];
    [self.navigationController pushViewController:reVC animated:YES];
}
- (void)changeBackFromRecoveryPassword
{
    [_listOfViewController removeLastObject];
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - Facebook & Twitter

- (void)changeToFacebookViewController {
    [[FBFunLoginManager Shared] reLogin];
    
    [_listOfViewController addObject:[[FBFunLoginManager Shared] getFBControllerWithDelegate:self]];
    [self.navigationController pushViewController:[[FBFunLoginManager Shared] getFBControllerWithDelegate:self] animated:YES];
}

- (void)chageBackFromFacebookViewController {
    if ([FBFunLoginManager Shared].loginStatus) {
        [_listOfViewController removeLastObject];
        [self.navigationController popViewControllerAnimated:NO];
        
		if ([FBFunLoginManager Shared].fName == nil || [FBFunLoginManager Shared].lName == nil || [FBFunLoginManager Shared].userID == nil) {
			ALERT(@"chageBackFromFacebookViewController", STRING_ALERT_DATA_IS_NIL);
			return;
		}
		
		NSMutableDictionary  *params = [NSMutableDictionary new];
        [params setObject:[FBFunLoginManager Shared].fName forKey:STRING_REQUEST_KEY_F_NAME];
		[params setObject:[FBFunLoginManager Shared].lName forKey:STRING_REQUEST_KEY_L_NAME];
		[params setObject:[FBFunLoginManager Shared].email forKey:STRING_REQUEST_KEY_EMAIL];
        [params setObject:[FBFunLoginManager Shared].gender forKey:STRING_REQUEST_KEY_GENDER];
        [params setObject:[FBFunLoginManager Shared].about forKey:STRING_REQUEST_KEY_ABOUT];
        if([FBFunLoginManager Shared].birthday)
        {
            NSDateComponents* ageComponents = [[NSCalendar currentCalendar]
                                               components:NSYearCalendarUnit
                                               fromDate:[FBFunLoginManager Shared].birthday
                                               toDate:[FBFunLoginManager Shared].updateTime
                                               options:0];
            NSInteger age = [ageComponents year];
            // set age
            [params setObject:[NSNumber numberWithInt:age] forKey:STRING_REQUEST_KEY_AGE];
        }
        else
        {
            [params setObject:[NSNumber numberWithInt:-1] forKey:STRING_REQUEST_KEY_AGE];
        }
    }
    else {
        [_listOfViewController removeLastObject];
        [self.navigationController popViewControllerAnimated:YES];
    }
}

/////////////////////////////////
- (void)changeToTwitterViewController {
    [[TWLoginManager Shared] reLogin];
    
    [_listOfViewController addObject:[[TWLoginManager Shared] getTWControllerWithDelegate:self]];
    [self.navigationController pushViewController:[[TWLoginManager Shared] getTWControllerWithDelegate:self] animated:YES];
}

- (void)chageBackFromTwitterViewController {
    if ([TWLoginManager Shared].loginStatus) {
        [_listOfViewController removeLastObject];
        [self.navigationController popViewControllerAnimated:NO];
        
		if ([TWLoginManager Shared].userName == nil) {
			ALERT(@"chageBackFromTwitterViewController", STRING_ALERT_DATA_IS_NIL);
			return;
		}
		
		NSMutableDictionary  *params = [NSMutableDictionary new];
        [params setObject:[TWLoginManager Shared].name forKey:STRING_REQUEST_KEY_F_NAME];
		[params setObject:@"" forKey:STRING_REQUEST_KEY_L_NAME];
		[params setObject:STRING_ID_TW_FORMATTER([TWLoginManager Shared].userID) forKey:STRING_REQUEST_KEY_EMAIL];
        [params setObject:[TWLoginManager Shared].gender forKey:STRING_REQUEST_KEY_GENDER];
        [params setObject:[TWLoginManager Shared].about forKey:STRING_REQUEST_KEY_ABOUT];
    }
    else {
        [_listOfViewController removeLastObject];
        [self.navigationController popViewControllerAnimated:YES];
    }
}

#pragma mark - UIImage Picker View Controller

- (void)changeToPickerControllerWithSourceType:(UIImagePickerControllerSourceType)type andDelegate:(id<UINavigationControllerDelegate, UIImagePickerControllerDelegate>)delegate {
    if ([UIImagePickerController isSourceTypeAvailable:type]) {
        UIImagePickerController *picker = [[UIImagePickerController alloc] init];
        picker.sourceType = type;
        picker.delegate = delegate;
        if ([UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceFront] && type == UIImagePickerControllerSourceTypeCamera) {
            picker.cameraDevice = UIImagePickerControllerCameraDeviceFront;
        }
        [self presentModalViewController:picker animated:NO];
    }
    else {
        ALERT(@"", STRING_ALERT_MESSAGE_CAMERA_PHOTO_NOT_SUPPORTED);
    }
}
- (void)changeBackFromPickerController {
    [self dismissModalViewControllerAnimated:NO];
}



#pragma mark - Application's Documents directory

// Returns the URL to the application's Documents directory.
- (NSURL *)applicationDocumentsDirectory
{
    return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}

- (NSURL *)applicationCacheDirectory
{
    return [[[NSFileManager defaultManager] URLsForDirectory:NSCachesDirectory inDomains:NSUserDomainMask] lastObject];
}

-(void)requestUpdateDeviceToken:(NSString*)oldToken
{
    if ([UserDataManager Shared].userID.length > 0) {
        NSLog(@"REQUEST Update Device token old = {%@} by new = {%@}", oldToken, [AppViewController Shared].configDataModel.deviceToken);
        NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
        
        [params setValue:[AppViewController Shared].configDataModel.deviceToken forKey:STRING_REQUEST_KEY_DEVICE_TOKEN];
        if([oldToken isEqualToString:@""])
        {
            [params setValue:[AppViewController Shared].configDataModel.deviceToken forKey:STRING_REQUEST_KEY_OLD_DEVICE_TOKEN];
        }
        else
        {
            [params setValue:oldToken forKey:STRING_REQUEST_KEY_OLD_DEVICE_TOKEN];
        }
        NSLog(@"requestUpdateDeviceToken-1 params = %@", params);
        
        NSString *url = [NSString stringWithFormat:@"%@/%@", STRING_REQUEST_URL_USER_UPDATE_DEVICE_TOKEN_DRIVER, [UserDataManager Shared].userID];
        
        [[APIRequester Shared] requestWithType:ENUM_API_REQUEST_TYPE_NOTIFICATION_UPDATE_DEVICE_TOKEN andRootURL:url andPostMethodKind:YES andParams:params andDelegate:self];
    }
}


#pragma mark - APIRequesterProtocol

- (void)requestFinished:(ASIHTTPRequest *)request andType:(ENUM_API_REQUEST_TYPE)type {
    NSLog(@"requestFinished %@, request.responseStatusCode: %i", request.responseString, request.responseStatusCode);
    
    [[AppViewController Shared] isRequesting:NO andRequestType:ENUM_API_REQUEST_TYPE_INVALID andFrame:CGRectZero];
    
    NSError *error;
    SBJSON *sbJSON = [SBJSON new];
    
    if (![sbJSON objectWithString:[request responseString] error:&error] || request.responseStatusCode != 200 || !request) {
//        if (![ASIHTTPRequest isNetworkReachable]) {
//            ALERT(STRING_ALERT_CONNECTION_ERROR_TITLE, STRING_ALERT_SERVER_ERROR);
//        }
        ALERT(STRING_ALERT_CONNECTION_ERROR_TITLE, STRING_ALERT_SERVER_ERROR);
        return;
    }
    
    if (type == ENUM_API_REQUEST_TYPE_NOTIFICATION_UPDATE_DEVICE_TOKEN)
    {
        NSLog(@"Update Device Token is Success.");
    }
    
}

- (void)requestFailed:(ASIHTTPRequest *)request andType:(ENUM_API_REQUEST_TYPE)type {
    NSLog(@"requestFailed %@, request.responseStatusCode: %i", request.responseString, request.responseStatusCode);
    
    [[AppViewController Shared] isRequesting:NO andRequestType:ENUM_API_REQUEST_TYPE_INVALID andFrame:CGRectZero];
    
    if (![ASIHTTPRequest isNetworkReachable]) {
        ALERT(STRING_ALERT_CONNECTION_ERROR_TITLE, STRING_ALERT_CONNECTION_ERROR);
    }
}

#pragma mark - Popup Animation
- (void)countDownAndDisplay
{
    NSLog(@"_remainingTime: %i", _remainingTime);
    
    if (_remainingTime <= 0) {
        _remainingTime = 0;
        int seconds = _remainingTime % TIMER_SEC_PER_MINUTE;
        int minutes = (_remainingTime - seconds) / TIMER_SEC_PER_MINUTE;
        
        if (_requestPopUpView) {
            _requestPopUpView.lblMinutes.text = [NSString stringWithFormat:@"%.2i", minutes];
            _requestPopUpView.lblSeconds.text = [NSString stringWithFormat:@"%.2i", seconds];
            
            _requestPopUpView.lblCountingDownTitle.textColor = [UIColor redColor];
            _requestPopUpView.lblCountingDownTitle.text = @"￼Time is up!";
        }
    }
    else
    {
        int seconds = _remainingTime % TIMER_SEC_PER_MINUTE;
        int minutes = (_remainingTime - seconds) / TIMER_SEC_PER_MINUTE;
        
        if (_requestPopUpView) {
            _requestPopUpView.lblMinutes.text = [NSString stringWithFormat:@"%.2i", minutes];
            _requestPopUpView.lblSeconds.text = [NSString stringWithFormat:@"%.2i", seconds];
        }
        
        _remainingTime -= 1;
    }
}

- (void)showPopupWithNotificationType:(enumRemoveNotificationType)type andRemoteNotification:(NSDictionary *)userInfo andDelegate:(id<RequestPopupViewDelegate>)delegate {
    if (_requestPopUpView.viewPopUp) {
        [_requestPopUpView.viewPopUp removeFromSuperview];
        _requestPopUpView = nil;
    }
    
    switch (type) {
        case enumRemoveNotificationType_ClientRequestDriver:
        {
            if (!userInfo) {
                return;
            }
            
            _requestPopUpView = [[RequestPopupView alloc] initWithNotificationType:type];
            _requestPopUpView.viewPopUp.frame = CGRectMake(0, [SupportFunction getDeviceHeight], [SupportFunction getDeviceWidth], [SupportFunction getDeviceHeight]);
            _requestPopUpView.delegate = delegate;
            float distance = [[userInfo valueForKey:@"distance"] floatValue];
            NSInteger estimatedTime = [[userInfo valueForKey:@"duration"] floatValue];
            NSString *distanceUnit = @"miles";
            if (distance <= 1) {
                distanceUnit = @"mile";
            }
            NSString *timeUnit = @"mins";
            if (estimatedTime <= 1) {
                timeUnit = @"min";
            }
            
            _requestPopUpView.distanceLbl.text = [NSString stringWithFormat:@"Distance: %.1f %@", distance, distanceUnit];
            _requestPopUpView.timeLbl.text = [NSString stringWithFormat:@"Estimated time: %d %@", estimatedTime, timeUnit];
            [self.navigationController.view addSubview:_requestPopUpView.viewPopUp];
            break;
        }
        case enumRemoveNotificationType_ClientCountDownPopup:
        case enumRemoveNotificationType_DriverCountDownPopup:
        {
            _requestPopUpView = [[RequestPopupView alloc] initWithNotificationType:type];
            
            _requestPopUpView.viewPopUp.frame = CGRectMake(([SupportFunction getDeviceWidth] - _requestPopUpView.viewPopUp.frame.size.width)/2, HEIGHT_STATUS_BAR + HEIGHT_HOME_VIEW_CONTROLLER_TITLE, _requestPopUpView.viewPopUp.frame.size.width, _requestPopUpView.viewPopUp.frame.size.height);
            _requestPopUpView.delegate = delegate;
            [self.navigationController.view addSubview:_requestPopUpView.viewPopUp];
            
            // Count Down
            if (![_timerCountDown isValid]) {
                _timerCountDown = [NSTimer scheduledTimerWithTimeInterval:TIMER_COUNT_DOWN_UNIT target:self selector:@selector(countDownAndDisplay) userInfo:nil repeats:YES];
            }
            _remainingTime = INT_DEFAULT_COUNTING_DOWN;
            _requestPopUpView.lblCountingDownTitle.textColor = [UIColor whiteColor];
            _requestPopUpView.lblCountingDownTitle.text = @"￼Counting down:";
            
            break;
        }
        default:
        {
            _requestPopUpView = [[RequestPopupView alloc] initWithNotificationType:type];
            _requestPopUpView.viewPopUp.frame = CGRectMake(0, [SupportFunction getDeviceHeight], [SupportFunction getDeviceWidth], [SupportFunction getDeviceHeight]);
            _requestPopUpView.delegate = delegate;
            [self.navigationController.view addSubview:_requestPopUpView.viewPopUp];
            break;
        }
    }
    
    if (type == enumRemoveNotificationType_ClientCountDownPopup || type == enumRemoveNotificationType_DriverCountDownPopup) {
        
    }
    else {
        [UIView beginAnimations:nil context:nil];
        [UIView setAnimationDuration:TIMER_CHANGING_VIEW];
        _requestPopUpView.viewPopUp.center = CGPointMake([SupportFunction getDeviceWidth]/2, [SupportFunction getDeviceHeight]/2);
        [UIView commitAnimations];
    }
    
    // Client, Driver pupup
    UIViewController *lastViewController = [_listOfViewController lastObject];
    UIView *popupView = nil;
    if ([lastViewController isKindOfClass:[DriverMainViewController class]]) {
        popupView = ((DriverMainViewController *)lastViewController).viewListPopup;
    }
    else if ([lastViewController isKindOfClass:[ClientMainViewController class]]) {
        popupView = ((ClientMainViewController *)lastViewController).viewListPopup;
    }
    
    if (popupView) {
        [self.navigationController.view bringSubviewToFront:popupView];
    }
}

- (void)hidePopupWithNotificationType:(enumRemoveNotificationType)type {
    if (_requestPopUpView) {
        [UIView beginAnimations:nil context:nil];
        [UIView setAnimationDuration:TIMER_CHANGING_VIEW];
        _requestPopUpView.viewPopUp.center = CGPointMake([SupportFunction getDeviceWidth]/2, [SupportFunction getDeviceHeight]*3/2);
        [UIView commitAnimations];
    }
}

#pragma mark - Remote Notification
- (void)didReceiveRemoteNotification:(NSDictionary *)userInfo andNotificationType:(enumRemoveNotificationType)type {
    UIViewController *lastViewController = [_listOfViewController lastObject];
    
    if ([lastViewController isKindOfClass:[DriverMainViewController class]]) {
        [((DriverMainViewController *)lastViewController) didReceiveRemoteNotification:userInfo andNotificationType:type];
    }
    else if ([lastViewController isKindOfClass:[ClientMainViewController class]]) {
        [((ClientMainViewController *)lastViewController) didReceiveRemoteNotification:userInfo andNotificationType:type];
    }
}

@end
